Param(
  [ValidateSet("packager","builder")] [string]$Mode = "builder",
  [string]$Icon = ".\build\icon.ico",
  [bool]$Clean = $true
)

$ErrorActionPreference = "Stop"

function Run($cmd) {
  Write-Host (">> " + $cmd)
  cmd /c $cmd
  if ($LASTEXITCODE -ne 0) {
    throw "Command failed ($LASTEXITCODE): $cmd"
  }
}

function Test-ValidIco($path) {
  try {
    $fs = [System.IO.File]::OpenRead($path)
    $br = New-Object System.IO.BinaryReader($fs)
    $reserved = $br.ReadUInt16()
    $type = $br.ReadUInt16()
    $count = $br.ReadUInt16()
    $br.Close()
    $fs.Close()
    return (($reserved -eq 0) -and ($type -eq 1) -and ($count -ge 1))
  } catch {
    return $false
  }
}

Write-Host "=== MarkGod build & pack (Windows) ==="

# Clean previous outputs
if ($Clean) {
  Write-Host "Cleaning output directories..."
  if (Test-Path "release\\markgod-win32-x64") { Remove-Item -Recurse -Force "release\\markgod-win32-x64" -ErrorAction SilentlyContinue }
  if (Test-Path "dist") { Remove-Item -Recurse -Force "dist" -ErrorAction SilentlyContinue }
  if (Test-Path "renderer") { Remove-Item -Recurse -Force "renderer" -ErrorAction SilentlyContinue }
}

# Build renderer (vite)
Write-Host "Building renderer (vite)..."
Run "npm run build"

# Build main process (TypeScript)
Write-Host "Building main process (tsc)..."
Run "npm run build:main"

# (Removed) Sync to project root
# 为保持目录整洁，移除了将 dist 内容拷贝到根目录的步骤。

# Generate icon.ico (multi-size) before packaging
Write-Host "Generating icon.ico..."
Run "node tools\generate-icon.js"
if (-not $Icon) { $Icon = ".\build\icon.ico" }

# Clean npm cache logs to avoid EPERM during packaging on Windows
if (Test-Path ".\.cache\npm\_logs") {
  Write-Host "Cleaning npm cache logs (.cache\\npm\\_logs)..."
  Remove-Item -Recurse -Force ".\.cache\npm\_logs" -ErrorAction SilentlyContinue
}

# Package application
Write-Host ("Packaging application (" + $Mode + ")...")
$PackSucceeded = $false
$OutBase = "release"

if ($Mode -eq "packager") {
  # 使用临时打包目录，避免扫描项目根导致权限或冗余问题
  $StageDir = Join-Path -Path (Get-Location).Path -ChildPath "pack_tmp"
  Write-Host ("StageDir set to: " + $StageDir)
  if (-not $StageDir) { $StageDir = ".\pack_tmp" }
  if ($StageDir -and (Test-Path $StageDir)) { Remove-Item -Recurse -Force $StageDir -ErrorAction SilentlyContinue }
  New-Item -ItemType Directory -Force -Path $StageDir | Out-Null
  
  Write-Host "Staging dist/ to pack_tmp..."
  Copy-Item -Recurse -Force "dist" (Join-Path $StageDir "dist")
  Write-Host "Staging node_modules/ to pack_tmp... (this may take a while)"
  Copy-Item -Recurse -Force "node_modules" (Join-Path $StageDir "node_modules")
  Write-Host "Staging package.json to pack_tmp..."
  Copy-Item -Force "package.json" (Join-Path $StageDir "package.json")
  if (Test-Path "README.md") { Copy-Item -Force "README.md" (Join-Path $StageDir "README.md") }
  if (Test-Path "build") { Copy-Item -Recurse -Force "build" (Join-Path $StageDir "build") }
  
  $cmd = "npx electron-packager `"$StageDir`" markgod --platform=win32 --arch=x64 --out=$OutBase --overwrite"
  if ($Icon -and (Test-Path $Icon) -and (Test-ValidIco $Icon)) { $cmd = "$cmd --icon `"$Icon`"" } else { Write-Warning "Skipping invalid icon: $Icon" }
  try {
    Run $cmd
    # 清理临时打包目录
    if ($StageDir -and (Test-Path $StageDir)) { Remove-Item -Recurse -Force $StageDir -ErrorAction SilentlyContinue }
    $PackSucceeded = $true
  } catch {
    Write-Warning "Packaging to '$OutBase' failed. Fallback to timestamped directory."
    $ts = Get-Date -Format "yyyyMMdd_HHmmss"
    $OutBase = "release_$ts"
    $cmd = "npx electron-packager `"$StageDir`" markgod --platform=win32 --arch=x64 --out=$OutBase --overwrite"
    if ($Icon -and (Test-Path $Icon) -and (Test-ValidIco $Icon)) { $cmd = "$cmd --icon `"$Icon`"" } else { Write-Warning "Skipping invalid icon: $Icon" }
    Run $cmd
    # 清理临时打包目录
    if ($StageDir -and (Test-Path $StageDir)) { Remove-Item -Recurse -Force $StageDir -ErrorAction SilentlyContinue }
    $PackSucceeded = $true
  }
} else {
  # electron-builder path (generates installer in release directory according to package.json config)
  # Icon is already generated by tools\generate-icon.js, no need to copy
  $cmd = "npx electron-builder --win"
  Run $cmd
  $PackSucceeded = $true
}

if ($PackSucceeded) {
  $outDir = Join-Path $OutBase "markgod-win32-x64"
  Write-Host ("Done. Output: " + $outDir)
  if (Test-Path $outDir) {
    Write-Host ("Run: `"" + (Join-Path $outDir "markgod.exe") + "`"")
  }
  Write-Host "Logs: $env:APPDATA\\markgod\\logs or '$(Resolve-Path .)\\logs'"
  exit 0
} else {
  Write-Error "Packaging failed."
  exit 1
}